package com.daka.controller;

import com.daka.entity.*;
import com.daka.enumerate.StatusCode;
import com.daka.service.*;
import com.daka.tools.AuctionEndLine;
import com.daka.tools.CookieUtil;
import com.daka.tools.DateUtil;
import com.daka.tools.SessionHolder;
import com.daka.vo.BaseResponseVo;
import com.daka.vo.DataResponseVo;
import com.daka.vo.ListDataResponseVo;
import com.daka.vo.db.UserInfoVo;
import com.daka.vo.request.UserWechartVo;
import com.daka.vo.response.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangx
 * CreateTime: 2016/12/12 17:09
 */

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private TeamService teamService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private OrderService orderService;
    @Resource
    private UserOpenService userOpenService;
    @Resource
    private AuctionTradeListService auctionTradeListService;
    @Resource
    private GoodsService goodsService;

    /**
     * 大区列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/areaList", consumes = "application/json")
    public ListDataResponseVo<AreaVo> areaList() {
        List<Team> list = teamService.selectArea();
        if (list.size() < 1) {
            return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
        } else {
            List<AreaVo> list1 = new ArrayList<>();
            AreaVo areaVoTemp = new AreaVo();
            areaVoTemp.setArea(999L);
            areaVoTemp.setAreaName("爱心人士");
            list1.add(areaVoTemp);
            for (Team team : list) {
                list1.add(AreaVo.build(team));
            }

            return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), list1);
        }
    }

    /**
     * 团队列表
     *
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/teamList", consumes = "application/json")
    public ListDataResponseVo<TeamSimpVo> teamList(@RequestBody Team param) {
        if (param.getArea() == null) {
            return new ListDataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        List<Team> list = teamService.selectByArea(param.getArea());
        if (list.size() < 1) {
            return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
        } else {
            List<TeamSimpVo> list1 = new ArrayList<>();
            for (Team team : list) {
                list1.add(TeamSimpVo.build(team));
            }
            return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), list1);
        }
    }

    /**
     * 团员列表
     *
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/userList", consumes = "application/json")
    public ListDataResponseVo<User> userList(@RequestBody User param) {
        if (param.getTeam() == null || param.getTeam() == 0) {
            return new ListDataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        List<User> list = userService.selectByTeam(param.getTeam());
        return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), list);
    }

    /**
     * 新增用户手机号、宣言
     *
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/update", consumes = "application/json")
    public ListDataResponseVo<User> update(@RequestBody User param) {
        if (param.getId() == null) {
            return new ListDataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }

        if(new Date().getTime() >= DateUtil.str2Date(AuctionEndLine.PAY_END_TIME,DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS).getTime()){
            return new ListDataResponseVo<>(StatusCode.SERVER_EXCEPTION.getCode(),"筹款已截止");
        }

        User user = userService.selectById(param.getId());
        user.setMobile(param.getMobile());
        user.setDeclaration(param.getDeclaration());
        int a = userService.updateById(user);
        return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
    }


    /**
     * 新增捐赠社会人员
     *
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/create", consumes = "application/json")
    public DataResponseVo<User> create(@RequestBody User param) {
        if (param.getName() == null) {
            return new DataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        User user = new User();
        user.setName(param.getName());
        user.setTeam(-1L);
        user.setMoney(new BigDecimal("0"));
        user.setStatus("1");
        user.setCreateUser("Admin");
        user.setCreateTime(new Date());
        if (param.getMobile() != null) {
            user.setMobile(param.getMobile());
        }
        if (param.getDeclaration() != null) {
            user.setDeclaration(param.getDeclaration());
        }
        int a = userService.save(user);
        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), user);
    }


    /**
     * 用户个人中心
     *
     * @param param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/queryDetail", consumes = "application/json")
    public DataResponseVo<Object> queryDetail(@RequestBody User param) {
        if (param.getId() == null) {
            return new DataResponseVo<>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }
        //用户信息
        User user = userService.selectById(param.getId());
        if (user == null) {
            return new DataResponseVo<>(StatusCode.USER_NOT_EXISTS.getCode(), StatusCode.USER_NOT_EXISTS.getMessage());
        }

        UserDetailVo userDetailVo = UserDetailVo.build(user);
        //团队名称
        if (user.getTeam() != null) {
            Team team = teamService.findById(user.getTeam());
            if (team != null && team.getName() != null) {
                userDetailVo.setTeamName(team.getName());
                userDetailVo.setTeamPic(team.getTeamPic());
            }
        }
        //排名
        List<User> list = userService.findBiggerByMoney(user.getMoney());
//
//        int a = 0;
//        for (int i = 0; i < list.size(); i++) {
//            if (i != 0) {
//                if (!Objects.equals(list.get(i - 1).getMoney(), list.get(i).getMoney())) {
//                    a = a + 1;
//                }
//            }
//        }
//        if(a == 0){
//            userDetailVo.setNumber(1);
//        }else {
//            userDetailVo.setNumber(a);
//        }

        if (list.size() == 0) {
            userDetailVo.setNumber(1);
        } else {
            int temp;
            User tempUser;
            tempUser = list.get(0);
            temp = 1;
            for (int i = 0; i < list.size(); i++) {
                if (i != 0) {
                    if (!Objects.equals(list.get(i).getMoney(), tempUser.getMoney())) {
                        tempUser = list.get(i);
                        temp = temp + 1;
                    }
                }
            }

            userDetailVo.setNumber(temp + 1);
        }


        //项目
        List<Project> listProject = projectService.findByUserIdGroup(user.getId());
        List<Project> retProject = new ArrayList<>();
        if (listProject.size() > 0) {
            for (Project project : listProject) {
                Order order = new Order();
                order.setProjectId(project.getId());
                order.setUserId(user.getId());
                List<Order> listOrder = orderService.selectByStatement(order);
                if (listOrder.size() > 0) {
                    project.setMoney(new BigDecimal("0"));
                    for (Order order1 : listOrder) {
                        project.setMoney(project.getMoney().add(order1.getMoney()));
                    }
                }
                //查询项目所在的图片
                if (project.getTeamId() != null) {
                    Team team = teamService.findById(project.getTeamId().longValue());
                    if (team != null && team.getTeamPic() != null) {
                        project.setTeamPic(team.getTeamPic());
                    }
                }
                project.setMoney(project.getMoney().divide(BigDecimal.valueOf(100)));
                retProject.add(project);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user", userDetailVo);
        map.put("project", retProject);
        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), map);
    }

    /**
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/queryAll", consumes = "application/json")
    public DataResponseVo<Object> queryAll() {

        List<UserInfoVo> list = userService.findUserInfoVo();
        List<UserInfoVo> retList = new ArrayList<>();
        UserInfoVo userInfoVo;
        int num = 1;
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                userInfoVo = list.get(0);
                userInfoVo.setNumber(num);
            } else {
                if (Objects.equals(list.get(i - 1).getMoney(), list.get(i).getMoney())) {
                    userInfoVo = list.get(i);
                    userInfoVo.setNumber(num);
                } else {
                    num = num + 1;
                    userInfoVo = list.get(i);
                    userInfoVo.setNumber(num);
                }
            }
            retList.add(userInfoVo);
        }
        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), retList);
    }

    /**
     * 全员捐款服务队
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/queryFullDonation", consumes = "application/json")
    public DataResponseVo<Object> queryFullDonation() {

        List<Team> listTeam = teamService.findList();
        List<TeamAndUserVo> retList = new ArrayList<>();


        if (listTeam.size() > 0) {
            for (Team team : listTeam) {
                TeamAndUserVo teamAndUserVo = new TeamAndUserVo();
                List<User> listUserDo = userService.selectByTeamDonated(team.getId());
                List<User> listUser = userService.selectByTeam(team.getId());
                if (listUser.size() > 0 && listUser.size() == listUserDo.size()) {
                    List<String> userName = new ArrayList<>();
                    for (User user : listUser) {
                        userName.add(user.getName());
                    }
                    teamAndUserVo.setTeamName(team.getName());
                    teamAndUserVo.setUserName(userName);
                    retList.add(teamAndUserVo);
                }
            }
        }
        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), retList);
    }

    /**
     * 新增用户微信绑定信息
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/addWechart", consumes = "application/json")
    public BaseResponseVo addWechart(@RequestBody UserWechartVo param, HttpServletRequest request) {

        String openId = SessionHolder.getOpenId();

        if (StringUtils.isEmpty(openId)) {
            return new BaseResponseVo(StatusCode.SERVER_EXCEPTION.getCode(), "用户信息不存在");
        }

        String headUrl = CookieUtil.getCookieHeadUrl(request);

        if (null == param.getUserId() || 0 == param.getUserId()) {
            User user = new User();
            user.setMobile(param.getMobile());
            user.setName(param.getUserName());
            user.setTeam(-1l);
            user.setStatus("1");
            user.setCreateTime(new Date());
            user.setCreateUser("Admin");
            user.setHeadUrl(headUrl);
            user.setMoney(BigDecimal.ZERO);
            userService.save(user);

            UserOpen userOpen = new UserOpen();
            userOpen.setOpenId(openId);
            userOpen.setUserId(user.getId());

            userOpenService.insert(userOpen);

        } else {
            UserOpen userOpen = userOpenService.selectByUserId(param.getUserId());
            if (null == userOpen) {
                userOpen = new UserOpen();
                userOpen.setOpenId(openId);
                userOpen.setUserId(param.getUserId());

                userOpenService.insert(userOpen);


                User user = userService.selectById(param.getUserId());
                user.setHeadUrl(headUrl);
                if (StringUtils.isNotEmpty(param.getMobile())) {
                    user.setMobile(param.getMobile());
                }
                userService.updateById(user);

            } else {
                return new BaseResponseVo(StatusCode.SERVER_EXCEPTION.getCode(), "用户已经进行过微信绑定");
            }
        }

        return new ListDataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
    }

    /**
     * 查询是否绑定微信信息
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/checkWechart", consumes = "application/json")
    public BaseResponseVo checkWechart() {

        String openId = SessionHolder.getOpenId();

        UserOpen userOpen = userOpenService.selectByOpenId(openId);
        if (null == userOpen) {
            return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), false);
        }
        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), true);
    }

    /**
     * 我的竞拍信息
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/myAuction", consumes = "application/json")
    public DataResponseVo<Object> myAuction() {

        String openId = SessionHolder.getOpenId();

        UserOpen userOpen = userOpenService.selectByOpenId(openId);
        User user = userService.selectById(userOpen.getUserId());

        List<AuctionTradeList> auctionTradeLists = auctionTradeListService.selectByUserId(user.getId());

        HashMap<Long, MyAuctionVo> myAuctionVoHashMap = new HashMap<>();

        for (AuctionTradeList auctionTradeList : auctionTradeLists) {
            Goods goods = goodsService.selectById(auctionTradeList.getGoods());

            Integer showStatus = 0;

            if (auctionTradeList.getAmount().compareTo(goods.getMaxAmount()) == -1) {
                showStatus = 10;
            } else if (auctionTradeList.getPayStatus() == 1) {
                showStatus = 50;
            } else if (auctionTradeList.getAmount().compareTo(goods.getMaxAmount()) == 0) {
                if (auctionTradeList.getPayFlag() == 1) {
                    if (auctionTradeList.getPayType() == 1 && goods.getType() != 1) {
                        showStatus = 30;
                    } else {
                        showStatus = 40;
                    }
                } else {
                    showStatus = 20;
                }
            }

            MyAuctionVo myAuctionVo = MyAuctionVo.build(auctionTradeList, goods, showStatus);

            if (myAuctionVoHashMap.containsKey(myAuctionVo.getGoods())) {
                if (myAuctionVo.getAmount().compareTo(myAuctionVoHashMap.get(myAuctionVo.getGoods()).getAmount()) > 0) {
                    myAuctionVoHashMap.put(myAuctionVo.getGoods(), myAuctionVo);
                }
            } else {
                myAuctionVoHashMap.put(myAuctionVo.getGoods(), myAuctionVo);
            }
        }

        //总金额
        BigDecimal totalMoney = goodsService.sumTotal();
        if (totalMoney == null) {
            totalMoney = new BigDecimal("0.00");
        }
        //竞拍总次数
        int count = auctionTradeListService.countAll();

        Long thisTime = new Date().getTime();
        Long endTime = DateUtil.str2Date(AuctionEndLine.AUCTION_END_TIME, DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS).getTime();
        long time = endTime - thisTime;
        if (time < 0) {
            time = 0;
        }

        List<MyAuctionVo> list1 = new ArrayList<>();
        for (Long key : myAuctionVoHashMap.keySet()) {
            list1.add(myAuctionVoHashMap.get(key));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("retList", list1);
        map.put("totalMoney", totalMoney);
        map.put("user", user);
        map.put("count", count);
        map.put("time", BigDecimal.valueOf(time).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_DOWN));
        return new DataResponseVo<>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), map);
    }
}



















